package com.shyroke.daydayzhuanweb.controller;

import cn.hutool.core.util.StrUtil;
import com.shyroke.daydayzhuanapi.constant.ProjectConst;
import com.shyroke.daydayzhuanapi.constant.RedisKeyPrefix;
import com.shyroke.daydayzhuanapi.dto.*;
import com.shyroke.daydayzhuanapi.entity.*;
import com.shyroke.daydayzhuanapi.mapper.LabelMapper;
import com.shyroke.daydayzhuanapi.mapper.ProjectMapper;
import com.shyroke.daydayzhuanapi.mapper.TypeMapper;
import com.shyroke.daydayzhuandao.respository.*;
import com.shyroke.daydayzhuansvc.service.IOSSService;
import com.shyroke.daydayzhuansvc.service.IProjectService;
import com.shyroke.daydayzhuansvc.service.impl.SpiderService;
import com.shyroke.daydayzhuansvc.util.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类名 ：管理员管理项目（免费/包赔）
 * 用法 ：
 * 创建人 ： shyroke
 * 时间：2018/12/28 12:38
 */
@Controller
@RequestMapping(value = "admin/project")
public class AdminProjectController {

    @Autowired
    private ProjectRepository projectRepository;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private TypeRepository typeRepository;
    @Autowired
    private IOSSService ossService;
    @Autowired
    private LabelRepository labelRepository;
    @Autowired
    private ProjectEndRepository projectEndRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SpiderService spiderService;
    @Autowired
    private SpiderProjectRepository spiderProjectRepository;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private LabelMapper labelMapper;
    @Autowired
    private TypeMapper typeMapper;
    @Autowired
    private AppRepository appRepository;

    @Value("${spider_img_suff}")
    private String spider_img_suff;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 跳转到免费项目管理的页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "free_list")
    public ModelAndView free_list(ModelAndView model,HttpSession session) {
        UserMain user = (UserMain)session.getAttribute("user");
        Set<RoleEntity> roleList = userRepository.findByName(user.getName()).getRoleList();
        boolean isAdmin = UserUtils.isAdmin2(roleList);

        model.addObject("isAdmin",isAdmin);
        model.setViewName("admin/project/free_list");

        return model;
    }

    /**
     * 跳转到名言短剧解析页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "end_list")
    public ModelAndView end_list(ModelAndView model) {
        model.setViewName("admin/project/end_list");

        return model;
    }

    /**
     * 获取所有标签和类型
     *
     * @return
     */
    @RequestMapping(value = "getLabelAndType")
    @ResponseBody
    public R getLabelAndType(String title) {

        List<TypeEntity> typeList = new ArrayList<>();
        Iterator<TypeEntity> iterator = typeRepository.findAll().iterator();
        while (iterator.hasNext()) {
            typeList.add(iterator.next());
        }
        List<LabelEntity> labelList = labelRepository.findByIsShowTitle(0);

        if(org.apache.commons.lang.StringUtils.isNotEmpty(title)){
            for (LabelEntity label : labelList) {
                String keys = label.getKeys();
                if(org.apache.commons.lang.StringUtils.isNotEmpty(keys)){
                    String[] keyArr = keys.split(",");
                    for (String key : keyArr) {
                        if(title.contains(key)){
                            label.setSelected(true);
                        }
                    }
                }
            }
        }

        Map<String, Object> labelTypeList = new HashMap<>();
        labelTypeList.put("typeList", typeList);
        labelTypeList.put("labelList", labelList);

        return R.ok("labelTypeList", labelTypeList);
    }

    /**
     * 获取所有标签和类型
     *
     * @return
     */
    @RequestMapping(value = "getLabelList")
    @ResponseBody
    public R getLabelList() {
        return R.ok("labelList", labelRepository.findByIsShowTitle(0));
    }

    /**
     * 获取所有标签和类型
     *
     * @return
     */
    @RequestMapping(value = "getLabelByTypeIdSelected")
    @ResponseBody
    public R getLabelByTypeIdSelected(Integer typeId,Integer projectId) {
        Optional<ProjectEntity> optionalProject = projectRepository.findById(projectId);
        if(optionalProject.isPresent()){
            ProjectEntity projectEntity = optionalProject.get();
            List<LabelEntity> labelList = labelRepository.findByIsShowTitle(0);
            for(LabelEntity l:labelList){
                for(LabelEntity selectLabel:projectEntity.getLabelList()){
                    if(selectLabel.getId().intValue() == l.getId().intValue()){
                        l.setSelected(true);
                    }
                }
            }
            return R.ok("labelList", labelList);
        }
      return R.error("id对应的实体为空");
    }


    /**
     * 加载免费项目的数据
     *
     * @return
     */
    @RequestMapping(value = "getNormalProjectList")
    @ResponseBody
    public TabelData<ProjectDto> getNormalProjectList(Page page, ProjectDto project, HttpSession session) {
        UserMain user = (UserMain)session.getAttribute("user");
        return  projectService.getNormalProjectList(page,project,user);

    }

    /**
     * 删除项目
     * @param project
     * @return
     */
    @RequestMapping(value = "delete")
    @ResponseBody
    @PermissionAnnotation(permissionName = "free:delete")
    public R delete(ProjectDto project){

        try {
            projectService.deleteById(project.getId());
        } catch (Exception e){
            logger.info("删除失败",e);
            return R.error("删除失败，失败原因="+e.getMessage());
        }

        return R.ok("删除成功");
    }


    /**
     * 免费项目详情
     * @param model
     * @param projectId
     * @return
     */
    @RequestMapping(value = "descAndEdit/{id}")
    public ModelAndView descAndEdit(ModelAndView model,@PathVariable("id")Integer projectId,HttpSession session){

        ProjectEntity project =   projectService.getProjectById(projectId);

        if(!StringUtils.isEmpty(project.getCover())){
            project.setCover(ossService.getImgUrl(project.getCover()));
        }

        UserMain user = (UserMain)session.getAttribute("user");
        Set<RoleEntity> roleList = userRepository.findByName(user.getName()).getRoleList();
        Boolean isAdmin = UserUtils.isAdmin2(roleList);

        ProjectDto dto = projectMapper.entityToDto(project);
        Document document = Jsoup.parse(dto.getContent());
        Elements elements = document.select("div.relation_div");
        for (Element element : elements) {
            String appIdStr = element.attr("data-id");
            if(StrUtil.isBlank(appIdStr)){
                continue;
            }
            String appId = appIdStr.replaceAll("app-", "");
            Optional<AppEntity> optionApp = appRepository.findById(Integer.valueOf(appId));
            if (!optionApp.isPresent()) {
                continue;
            }
            AppEntity appEntity = optionApp.get();
            element.tagName("p");
            element.text("@@"+appEntity.getTitle());
        }
        dto.setContent(document.html());


        model.addObject("project",dto);
        model.addObject("isAdmin",isAdmin);
        model.addObject("typeList", projectService.getTypeList(project.getTypeObj().getId()));
        model.addObject("topLabels", projectService.getTopLables());
        model.setViewName("admin/project/free_project_desc_edit");

        return model;
    }


    /**
     * 跳转到新增免费项目页面
     * @param model
     * @return
     */
    @RequestMapping(value = "freeToAdd")
    public ModelAndView freeToAdd(ModelAndView model,String source,Integer projectId){
        model.addObject("source",source);
        model.addObject("projectId",projectId);
        model.addObject("typeList", projectService.getTypeList(null));
        model.addObject("topLabels", projectService.getTopLables());
        model.setViewName("admin/project/free_add");

        return model;
    }

    /**
     * 保存图片
     * @param request
     * @param file
     * @return
     */
    @RequestMapping(value = "uploadImg",method = RequestMethod.POST)
    @ResponseBody
    public R uploadImg(HttpServletRequest request, @RequestParam("file")MultipartFile file,String type){

        if(file.isEmpty()){
            return R.error("图片不能为空！");
        }

        String fileName = file.getOriginalFilename();

        //防止图片地址的字符被转义，比如a(1).png会被转义成a%281%29.png,导致显示错误。
        try {
            if(fileName!=null){
                fileName = URLDecoder.decode(fileName,"utf-8");
            }
        }catch (Exception e){
            logger.info("转义失败，原因="+ExceptionUtil.getMessage(e));
            return R.error("转义失败");
        }

        String ossPath = null;
        if(type == null){
            ossPath = OSSClientConstants.COVER_PATH;
        }else if("appCover".equals(type)){
            ossPath = OSSClientConstants.APP_COVER_PATH;
        }else if("appInvateImg".equals(type)){
            ossPath = OSSClientConstants.APP_INVATE_PATH;
        }else if("subjectCover".equals(type)){
            ossPath = OSSClientConstants.SUBJECT_COVER_PATH;
        }else{
            return R.error("type类型错误！");
        }

        String path = null;
        if("blob".equals(fileName)){
            fileName = CommonUtil.getUUID()+".png";
            path = ossPath+fileName;
        }else {
            //获取上传图片的后缀，比如.png,.jpg
            String img_suff = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            //获取随机产生的图片名字
            path = ossPath+RandomUtil.getRandomFileName()+img_suff;
        }

        try {
            ossService.uploadImg(file,path);
        }catch (Exception e){
            logger.info(ExceptionUtil.getMessage(e));
            return  R.error("上传图片失败，原因="+e.getMessage());
        }


        return R.ok("url",path);
    }

    /**
     * 保存免费项目
     * @param project
     * @return
     */
    @PermissionAnnotation(permissionName = "free:add")
    @RequestMapping(value = "free_project_save")
    @ResponseBody
    public R free_project_save(@RequestBody ProjectDto project, HttpSession session) throws UnsupportedEncodingException {

        UserMain user = (UserMain)session.getAttribute("user");
        Date currenDate = new Date();

        if(user == null){
            return R.error("登录超时！请重新登录");
        }

        project.setType(ProjectConst.NORMAL_PROJECT); //标志为普通项目
        project.setCreateTime(currenDate); //设置创建时间
        project.setReadMount(0);//阅读数量
        project.setCommentMount(0);//评论数量
        project.setCreateId(user.getId());//创建人ID
        project.setOffline(ProjectConst.UNOFFLINE); //默认未下架
        project.setUpdateTime(currenDate);

        if(user.getId() == 30) {
            return R.error("文章内容解析失败，请稍后重试。");
        }

        String title = project.getTitle();
        Document document = Jsoup.parse(project.getContent());
        Elements elements = document.select("img");
        if(elements!=null&&elements.size()>0){
            for(int i= 0;i<elements.size();i++){
                Element element = elements.get(i);
                element.attr("alt",title+"  第"+(i+1)+"张");
            }
            project.setContent(document.html());
        }
        try {
            project.setContent(EmojiTransferUtil.emojiEncode(project.getContent()));
            projectService.save(project);
        }catch (Exception e){
            logger.info(ExceptionUtil.getMessage(e));
            return R.error("保存失败，原因="+e.getMessage());
        }


        return R.ok("保存成功！");
    }

    /**
     * 保存标签
     * @return
     */
    @RequestMapping(value = "saveLabel")
    @ResponseBody
    public R saveLabel(String labelName){

        if(StringUtils.isEmpty(labelName)){
            return R.error("标签不能为空！");
        }

        //是否重复
        LabelEntity label2 = labelRepository.findByLabelName(labelName);
        if(label2 != null){
            return R.error("该标签名已经存在！");
        }

        LabelEntity label = new LabelEntity();
        label.setLabelName(labelName);
        label.setIsShowTitle(0);
        try {
            labelRepository.save(label);
            //删除redis
            redisTemplate.delete(RedisKeyPrefix.LABELLIST);
        }catch (Exception e){
            logger.info("保存标签失败:{}",e.getMessage());
            return R.error("保存标签失败！");
        }

        return R.ok("保存成功！");
    }



    /**
     * 保存爬虫爬取的项目
     * @param project
     * @return
     */
    @PermissionAnnotation(permissionName = "free:add")
    @RequestMapping(value = "free_project_save_bySpider")
    @ResponseBody
    public R free_project_save_bySpider(@RequestBody ProjectDto project, HttpSession session){

        UserMain user = (UserMain)session.getAttribute("user");
        Date currenDate = new Date();

        if(user == null){
            return R.error("登录超时！请重新登录");
        }

        project.setType(ProjectConst.NORMAL_PROJECT); //标志为普通项目
        project.setCreateTime(currenDate); //设置创建时间
        project.setReadMount(0);//阅读数量
        project.setCommentMount(0);//评论数量
        project.setCommented("0");
        project.setCreateId(user.getId());//创建人ID
        project.setOffline(ProjectConst.UNOFFLINE); //默认未下架
        project.setUpdateTime(currenDate);

        try {
            ossService.handleImg(project,null);
            Integer spiderProjectId = project.getSpiderProjectId();
            projectService.save(project);
            if(spiderProjectId != null){
                SpiderProjectEntity spiderProject = spiderService.findById(spiderProjectId);
                spiderProject.setIsSave(1);
                spiderProjectRepository.save(spiderProject);
            }
        }catch (Exception e){
            logger.info(ExceptionUtil.getMessage(e));
            return R.error("保存失败，原因="+e.getMessage());
        }


        return R.ok("保存成功！");
    }



    /**
     * 获取所有标签和类型
     *
     * @return
     */
    @RequestMapping(value = "getLabelAndTypeAndSelected/{id}")
    @ResponseBody
    public R getLabelAndTypeAndSelected(@PathVariable(value = "id",required = false)Integer projectId) {

        if(projectId == null){
            return R.error("项目id不能为空！");
        }

        //获取该项目的标签以及类型
        Optional<ProjectEntity> optionalProject = projectRepository.findById(projectId);
        if(!optionalProject.isPresent()){
            return R.error("id对应实体为空,id:"+projectId);
        }
        ProjectEntity project = optionalProject.get();

        List<LabelEntity> labelList = labelRepository.findByIsShowTitle(0);
        List<LabelDto> labelDtoList = labelList.stream().map(e -> labelMapper.entityToDto(e)).collect(Collectors.toList());
        for(LabelDto l:labelDtoList){
            for(LabelEntity selectLabel:project.getLabelList()){
                if(selectLabel.getId().intValue() == l.getId().intValue()){
                    l.setSelected(true);
                }
            }
        }

        Map<String, Object> labelTypeList = new HashMap<>();
        labelTypeList.put("typeList", projectService.getTypeList(project.getTypeObj().getId().intValue()));
        labelTypeList.put("labelList", labelDtoList);

        return R.ok("labelTypeList", labelTypeList);
    }


    /**
     * 修改免费项目
     * @param project
     * @return
     */
    @RequestMapping(value = "free_project_update")
    @ResponseBody
    public R free_project_update(@RequestBody ProjectAddRequest project){
        //过滤图片地址htttps/http+oss-cn-shenzhen.aliyuncs.com开头
       project.setCover(CommonUtil.deleteOSSImgPre(project.getCover()));

        //防止图片地址的字符被转义，比如a(1).png会被转义成a%281%29.png,导致显示错误。
        try {
            if(project.getCover()!=null){
                project.setCover(URLDecoder.decode(project.getCover(),"utf-8"));
            }
            if(project.getContent()!=null){
                String content = project.getContent();
                content = content.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                content = content.replaceAll("\\+", "%2B");
                project.setContent(content);
                project.setContent(URLDecoder.decode(project.getContent(),"utf-8"));
            }
        }catch (Exception e){
            logger.info("转义失败，原因="+ExceptionUtil.getMessage(e));
            return R.error("转义失败");
        }
        try {
            project.setContent(EmojiTransferUtil.emojiEncode(project.getContent()));
            projectService.update(project);
        }catch (Exception e){
            logger.info(ExceptionUtil.getMessage(e));
            return R.error("修改失败，原因="+e.getMessage());
        }


        return R.ok("修改成功！");
    }


    /**
     * 保存项目内容的图片
     * @param file
     * @return
     */
    @RequestMapping(value = "uploadProjectImg")
    @ResponseBody
    public LayEditRespon uploadProjectImg(MultipartFile file){
        LayEditRespon respon = new LayEditRespon();

        if(file.isEmpty()){
            respon.setCode(-1);
            respon.setMsg("图片为空");
            return respon;
        }

        String fileName = file.getOriginalFilename();

        //获取上传图片的后缀，比如.png,.jpg
        String img_suff = fileName.substring(fileName.lastIndexOf("."),fileName.length());

        //获取随机产生的图片名字
        String saveFileName = RandomUtil.getRandomFileName()+img_suff;


        String path = OSSClientConstants.CONTENT_PATH+CommonUtil.getDateByFormat(new Date(),"yyyy-MM-dd")+"/"+saveFileName;
        String url;
        try {
            ossService.uploadImg(file,path);
            url = ossService.getImgUrl(path);
            //加水印
            url = url + OSSClientConstants.WATER_MARK;
        }catch (Exception e){
            logger.info(ExceptionUtil.getMessage(e));
            respon.setCode(-1);
            respon.setMsg("图片上传失败");
            return respon;
        }

        Map<String,Object> data = new HashMap<String,Object>();

        data.put("src",url);

        respon.setCode(0);
        respon.setMsg("保存成功");
        respon.setData(data);

        return respon;
    }


    /**
     * 保存项目内容的图片
     * @param file
     * @return
     */
    @RequestMapping(value = "uploadProjectImg2")
    @ResponseBody
    public Map<String,Object> uploadProjectImg2(MultipartFile file){
        Map<String,Object> result = new HashMap<String,Object>();
        if(file.isEmpty()){
            result.put("errno",1);
            return result;
        }

        String fileName = file.getOriginalFilename();

        //获取上传图片的后缀，比如.png,.jpg
        String img_suff = fileName.substring(fileName.lastIndexOf("."),fileName.length());

        //获取随机产生的图片名字
        String saveFileName = RandomUtil.getRandomFileName()+img_suff;


        String path = OSSClientConstants.CONTENT_PATH+CommonUtil.getDateByFormat(new Date(),"yyyy-MM-dd")+"/"+saveFileName;
        String url;
        try {
            ossService.uploadImg(file,path);
            url = ossService.getImgUrl(path);
            //加水印
            url = url + OSSClientConstants.WATER_MARK;
        }catch (Exception e){
            logger.info(ExceptionUtil.getMessage(e));
            result.put("errno",1);
            return result;
        }


        String[] urlArr = new String[]{url};

        result.put("errno",0);
        result.put("data",urlArr);

        return result;
    }

    /**
     * 解析短语
     * @return
     */
    @RequestMapping(value = "analyzeContents")
    @ResponseBody
    public R analyzeContents(String contents){
        if(StringUtils.isEmpty(contents)){
            return R.error("内容不能为空！");
        }
        try {
            this.anaylze(contents);
        }catch (Exception e){
            logger.info("解析异常:",e);
            return R.error("解析异常");
        }
        return R.ok("解析并保存成功！");
    }

    private void anaylze(String contents) {
        String[] contentArr = contents.split("\\n\\n");
        ProjectEndEntity end = null;
        for(String content:contentArr){
            //去除1、 2、前缀
            if(content.indexOf("、") != -1){
                content = content.substring(content.indexOf("、")+1);
            }
            end = new ProjectEndEntity();
            end.setContent(content);
            projectEndRepository.save(end);
        }
    }

    /**
     * 下架
     *
     * @return
     */
    @RequestMapping(value = "unline")
    @ResponseBody
    public R unline(Integer projectId,HttpSession session) {
        UserMain user = (UserMain)session.getAttribute("user");
        Set<RoleEntity> roleList = userRepository.findByName(user.getName()).getRoleList();
        Boolean isAdmin = UserUtils.isAdmin2(roleList);

        Optional<ProjectEntity> optionalProject = projectRepository.findById(projectId);
        if(!optionalProject.isPresent()){
            return R.error("id对应的实体为空,id:"+projectId);
        }
        ProjectEntity project = optionalProject.get();
        if(!isAdmin && project.getCreateId().intValue() != user.getId().intValue()){
            return R.error("沒有操作权限！");
        }
        project.setOffline(ProjectConst.OFFLINE);
        project.setIsHomePage("0");
        String content = project.getContent();
        content = "<span style='color:red'>【黄了，不要玩了】</span>"+content;
        project.setContent(content);
        project.setUpdateTime(new Date());

        projectRepository.save(project);

        //删除置顶文章
        redisTemplate.delete(RedisKeyPrefix.PROJECT_RECOMMENTED);

        return R.ok("操作成功！");
    }

    /**
     * 跳转到草稿项目的页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "temp_list")
    public ModelAndView tempList(ModelAndView model,HttpSession session) {
        UserMain user = (UserMain)session.getAttribute("user");
        Set<RoleEntity> roleList = userRepository.findByName(user.getName()).getRoleList();
        boolean isAdmin = UserUtils.isAdmin2(roleList);

        model.addObject("isAdmin",isAdmin);
        model.setViewName("admin/project/temp_list");

        return model;
    }

    /**
     * 加载草稿项目的数据
     *
     * @return
     */
    @RequestMapping(value = "getTemProjectList")
    @ResponseBody
    public TabelData<ProjectDto> getTemProjectList() {
        return  projectService.getTemProjectList();
    }

    /**
     * 发布
     * @param title
     * @return
     */
    @RequestMapping(value = "publish")
    @ResponseBody
    public R publish(String title){
        if(StringUtils.isEmpty(title)){
            return R.error("标题不能为空！");
        }
        try {
            List<ProjectDto> temProjectList = RedisUtils.readList(RedisKeyPrefix.PROJECTTEMLIST);
            if(temProjectList != null){
                Iterator<ProjectDto> iterator = temProjectList.iterator();
                while (iterator.hasNext()){
                    ProjectDto next = iterator.next();
                    if(title.equals(next.getTitle())){
                        //更新为非草稿项目
                        next.setIsTemp("0");
                        next.setCreateTime(new Date());
                        //保存项目
                        projectService.save(next);
                        //更新缓存
                        iterator.remove();
                        break;
                    }
                }
                redisTemplate.opsForValue().set(RedisKeyPrefix.PROJECTTEMLIST,temProjectList);
            }

        } catch (Exception e){
            logger.info("发布失败",e);
            return R.error("发布失败，失败原因="+e.getMessage());
        }

        return R.ok("发布成功");
    }

    @RequestMapping(value = "setIsShowHome")
    @ResponseBody
    public R setIsShowHome(@RequestParam Integer id ,@RequestParam String isHomePage){
        ProjectEntity project = projectService.getProjectById(id);
        if(project == null){
            return R.error("没有找到该文章!");
        }
        project.setIsHomePage(isHomePage);
        projectRepository.save(project);
        return R.error("修改成功！");
    }

    @RequestMapping(value = "setProfit")
    @ResponseBody
    public R setProfit(@RequestParam Integer id ,@RequestParam BigDecimal profit){
        ProjectEntity project = projectService.getProjectById(id);
        if(project == null){
            return R.error("没有找到该文章!");
        }
        project.setProfit(profit);
        projectRepository.save(project);
        //删除今日可赚
        redisTemplate.delete(RedisKeyPrefix.PROFIT_TODAY);
        return R.error("修改成功！");
    }

    @RequestMapping(value = "setSortIndex")
    @ResponseBody
    public R setSortIndex(@RequestParam Integer id ,@RequestParam Integer sortIndex){
        ProjectEntity project = projectService.getProjectById(id);
        if(project == null){
            return R.error("没有找到该文章!");
        }
        project.setSortIndex(sortIndex);
        projectRepository.save(project);
        return R.error("修改成功！");
    }

    @RequestMapping(value = "setRecommend")
    @ResponseBody
    public R setRecommend(@RequestParam Integer id ,@RequestParam String recommend){
        ProjectEntity project = projectService.getProjectById(id);
        if(project == null){
            return R.error("没有找到该文章!");
        }
        project.setCommented(recommend);
        projectRepository.save(project);

        //删除置顶文章
        redisTemplate.delete(RedisKeyPrefix.PROJECT_RECOMMENTED);
        return R.error("修改成功！");
    }

    @RequestMapping(value = "updateProfit")
    @ResponseBody
    public R updateProfit(){
        return projectService.updateProfit();
    }

}
